import * as echarts from '../../../components/echarts/echarts';

const app = getApp();
const requestUtil = require("../../../utils/request");
const api = require("../../../config/api");
const common = require("../../../utils/common");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    examInfo: {}, // 学生的examInfo
    tableData: null,
    scoreRate: null, // 得分率
    everySubjectScoreRate: null, // 各科得分率
    examName: '无数据',
    examDate: null,
    examFullScoreArray: null,
    subjectArray: null,
    navigatorSubjectArray: null,
    studentName: '',
    examStudentNum: '',
    subjectEnglishNameMap: null,
    studentScoreTableHeader: [{
      prop: 'subjectName',
      width: 150,
      label: '科目',
    }, {
      prop: 'subjectScore',
      width: 150,
      label: '成绩',
    }, {
      prop: 'gradeRank',
      width: 150,
      label: '级排名',
    }, {
      prop: 'classRank',
      width: 150,
      label: '班排名',
    }, {
      prop: 'avgScore',
      width: 150,
      label: '班平均分',
    }, {
      prop: 'gradeAvgScore',
      width: 150,
      label: '级平均分',
    }, {
      prop: 'highestScore',
      width: 150,
      label: '最高分',
    }], // 考试概况表格
    tableNoDataMsg: '暂无数据~',
    border: true,
    studentScore: [], // 考试概况数据
    subjectIndex: 0, // 切换科目索引
    subjectArray: [], // 切换科目数组
    compareIndex: 0, // 对比项索引
    compareArray: [{
        colorName: 'olive',
        name: '班平均分',
        color: '#8dc63f'
      }, {
        colorName: 'pink',
        name: '级平均分',
        color: '#e03997'
      },
      //  {
      //   colorName: 'mauve',
      //   name: '班最低分',
      //   color: '#9c26b0'
      // }, 
      {
        colorName: 'cyan',
        name: '班最高分',
        color: '#1cbbb4'
      }
    ], // 对比项数组
    goodSubjectNameArray: [], // 获得良好科目的名称（通过ListData）
    goodSubjectComment: '', // 良好科目评价
    badSubjectNameArray: [], // 获得较差科目的名称（通过ListData）
    badSubjectComment: '', // 较差科目评价
    subjectRadarIsShow: true, // 控制科目subjectChart是否显示
    subjectRadar: { // subjecCharts的渲染
      onInit: function (canvas, width, height, dpr) {
        let data = getCurrentPages()[getCurrentPages().length - 1].data;
        const radarChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr
        });
        canvas.setChart(radarChart);
        radarChart.setOption(getRadarChartOption(data));
        return radarChart;
      }
    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let params = {
      grade: options.grade,
      examId: options.examId,
      schoolId: common.getSchoolId(),
      clazz: common.getClazz(),
      studentId: options.studentId,
      gradeType: options.studyType
    }
    this.getStudentExamScore(params);
    this.setData({
      params: params,
      subjectEnglishNameMap: app.globalData.subjectEnglishNameMap()
    })
  },

  /**
   * 查询学生成绩
   */
  async getStudentExamScore(params) {
    let studentScoreList = await requestUtil.request('POST', api.getStudentExamScore, params);
    let examInfo = studentScoreList.data.data.examInfo;
    let studentScore = studentScoreList.data.data.studentScore;

    if (studentScore == null || !studentScore.length > 0) {
      wx.showModal({
        title: '警告',
        content: '未找到该场考试的相关成绩，请等待教师上传成绩后再次打开。'
      })
      return;
    }

    let examName = examInfo.examName; // 考试名称
    let examDate = examInfo.regClosingTime; // 注册截止时间
    let examFullScoreArray = examInfo.examFullScore.split(','); // 各科满分值
    let subjectArray = examInfo.examSubject.split(','); // 科目数组
    let studentName = studentScore[0].studentName; // 学生名字
    let examStudentNum = studentScore[0].examStudentNum; // 考试人数
    let totalScore = 0; // 全科总分 
    let everySubjectScoreRate = []; // 各科得分率
    for (let i of examFullScoreArray) {
      totalScore += Number(i);
    }
    for (let j in subjectArray) {
      let item = this.data.subjectEnglishNameMap.get(subjectArray[j]) + 'Score';
      let score = studentScore[0][item];
      let scoreRate = ((score / examFullScoreArray[j]*100).toFixed(2)).toString() + '%';
      let obj = {
        subjectName: subjectArray[j],
        scoreRate: scoreRate
      }
      everySubjectScoreRate.push(obj);
    }
    let scoreRate = ((studentScore[0].sumScore / totalScore) * 100).toFixed(2); // 得分率

    let navigatorSubjectArray = subjectArray.slice(0);
    navigatorSubjectArray.unshift('总分');
    // 处理表格数据
    this.setTableData(studentScore, subjectArray);
    this.setData({
      examInfo,
      studentScore,
      examName,
      examDate,
      examFullScoreArray,
      navigatorSubjectArray,
      subjectArray,
      studentName,
      examStudentNum,
      everySubjectScoreRate,
      scoreRate: scoreRate + '%'
    })
    // 设置优秀科目与考差的科目评论的数组
    this.setSubjectNameArray();
  },

  /**
   * 处理表格数据
   */
  setTableData: function (studentScore, subjectArray) {
    let tableData = [];
    for (let i in subjectArray) {
      let subjectEnglish = this.data.subjectEnglishNameMap.get(subjectArray[i]);
      for (let j of studentScore[0].scoreAvgList) {
        if (subjectArray[i] == j.subjectName) {
          let obj = {
            subjectName: j.subjectName,
            subjectScore: studentScore[0][subjectEnglish+"Score"],
            classRank: studentScore[0][subjectEnglish + 'ClassRank'],
            gradeRank: studentScore[0][subjectEnglish + 'Rank'],
            avgScore: j.avgScore,
            highestScore: j.highestScore,
            gradeAvgScore: j.gradeAvgScore
          }
          tableData.push(obj);
          break;
        }
      }

    }
    let totalScore = {
      subjectName: '总分',
      subjectScore: studentScore[0].sumScore,
      classRank: studentScore[0].classRank,
      avgScore: '',
      highestScore: '',
      gradeAvgScore: '',
      gradeRank: studentScore[0].gradeRank
    }
    tableData.push(totalScore);
    this.setData({
      tableData,
    })
  },

  /**
   * 设置data中的 goodSubjectNameArray 和 badSubjectNameArray
   * @description 用特优率、优秀率、及格率、低分率（小于40）和各科排名比较
   */
  setSubjectNameArray: function () {
    let that = this;
    let bestArr = [];
    let goodArr = [];
    let badArr = [];
    let objArr = [];
    let studentInfo = this.data.studentScore[0];
    let examScoreRate = this.data.examInfo.examScoreRate.split(',');
    let examStudentNum = studentInfo.examStudentNum; // 考试人数
    // 考试人数 * 评价比率 = 评价得分率
    let compareObj = {
      best: examScoreRate[0] / 100 * examStudentNum, // 特优
      good: examScoreRate[1] / 100 * examStudentNum, // 优秀
      pass: examScoreRate[2] / 100 * examStudentNum, // 及格
      low: examStudentNum - examScoreRate[3] / 100 * examStudentNum // 低分
    }
    // 用于排列顺序
    for (let i in this.data.subjectArray) {
      for (let j of studentInfo.scoreAvgList) {
        if (this.data.subjectArray[i] == j.subjectName) {
          objArr.push(this.data.subjectEnglishNameMap.get(this.data.subjectArray[i]) + 'Rank')
        }
      }
    }
    for (let index in objArr) {
      let rank = studentInfo[objArr[index]];
      if (rank < compareObj.best) {
        bestArr.push(this.data.subjectArray[index]);
      } else if (rank < compareObj.good || rank < compareObj.pass) {
        goodArr.push(this.data.subjectArray[index]);
      } else if (rank > compareObj.low) {
        badArr.push(this.data.subjectArray[index]);
      }
    }
    let comment = '';
    if (bestArr.length > 0) {
      comment += bestArr.toString().replaceAll(',', '、') + "非常优秀，要保持哦~"
    }
    if (goodArr.length > 0) {
      comment += goodArr.toString().replaceAll(',', '、') + "比较优秀，要加油哦~"
    }
    that.setData({
      goodSubjectNameArray: goodArr.concat(bestArr),
      goodSubjectComment: comment,
      badSubjectNameArray: badArr,
      badSubjectComment: badArr.toString().replaceAll(',', '、') + "还需要重点强化学习，加油！"
    })
  },

  /**
   * 科目概况选择项
   */
  bindPickerChange: function (b) {
    let index = b.detail.value
    this.setData({
      compareIndex: index,
      subjectRadarIsShow: false
    });
    // 通过wx:if控制canvas的显示与否，可以重新渲染
    // 这里分开setData才能有效
    this.setData({
      subjectRadarIsShow: true
    });
  },

  /**
   * 跳转科目分数详情
   */
  toSubjectDetail: function (o) {
    let inType = o.type; // 点按钮还是切换
    let subjectName = '';
    let studentId = this.data.params.studentId;
    let schoolId = this.data.params.schoolId;
    let gradeType = this.data.params.gradeType;
    let grade = this.data.params.grade;
    let examId = this.data.params.examId;
    switch (inType) {
      case "change":
        subjectName = this.data.navigatorSubjectArray[o.detail.value]
        if (subjectName == '总分') {
          return;
        }
        break;
      case "tap":
        subjectName = o.currentTarget.dataset.name;
        break;
    }
    // 重置picker
    this.setData({
      subjectIndex: 0
    })
    wx.navigateTo({
      url: '../student-subject-score/score?studentId=' + studentId +
        '&schoolId=' + schoolId +
        '&gradeType=' + gradeType +
        '&grade=' + grade +
        '&examId=' + examId +
        '&subjectName=' + subjectName
    })
  }
})

function getRadarChartOption(d) {
  let indicatorArray = setIndicatorArray(d.examFullScoreArray, d.subjectArray);
  let scoreArray = setScoreObj(d.studentScore[0], d.compareArray[d.compareIndex].name, d.subjectArray, d.subjectEnglishNameMap);
  return {
    backgroundColor: "#ffffff",
    tooltip: {
      show: true,
      trigger: 'item',
      confine: true
    },
    xAxis: {
      show: false
    },
    yAxis: {
      show: false
    },
    radar: {
      // shape: 'circle',
      indicator: indicatorArray
    },
    symbol: "none", // 标记图形，"circle"
    series: [{
      name: '科目概况',
      type: 'radar',
      data: [{
        name: '我的分数',
        value: scoreArray.myScoreArr,
        itemStyle: {
          color: "#fbbd08"
        },
        lineStyle: {
          width: 4,
        },
        // areaStyle: {
        //   color: "#fbbd08"
        // }
      }, {
        name: d.compareArray[d.compareIndex].name,
        value: scoreArray.scoreArr,
        lineStyle: {
          width: 0
        },
        itemStyle: {
          color: d.compareArray[d.compareIndex].color
        },
        areaStyle: {
          opacity: 0.2,
          color: d.compareArray[d.compareIndex].color
        }
      }]
    }]
  };
}

/**
 * 用于获取和设置radar雷达图中的indicator的数组
 */
function setIndicatorArray(scoreArr, subjectArr) {
  let radarSettingArray = [];
  for (let i in subjectArr) {
    let obj = {
      name: subjectArr[i],
      max: scoreArr[i]
    }
    radarSettingArray.push(obj);
  }
  return radarSettingArray;
}

/**
 * 用于设置radar雷达图中的数据
 * @param myData Page.data.studentScore
 * @param name Page.data.compareArray中的name
 * @param subjectArr Page.data.subjectArray，用来对比key
 * @param englishArr Page.data.subjectEnglishNameMap
 */
function setScoreObj(myData, name, subjectArr, subjectEnglishNameMap) {
  let myScoreArr = [];
  let scoreArr = [];

  for (let obj of myData.scoreAvgList) {
    if ("班平均分" === name) {
      scoreArr.push(obj.avgScore);
    } else if ("班最低分" === name) {
      scoreArr.push(obj.lowestScore);
    } else if ("班最高分" === name) {
      scoreArr.push(obj.highestScore);
    } else if ("级平均分" === name) {
      scoreArr.push(obj.gradeAvgScore);
    }
    for (let i in subjectArr) {
      if (subjectArr[i] == obj.subjectName) {
        let str = subjectEnglishNameMap.get(subjectArr[i]) + 'Score';
        myScoreArr.push(myData[str])
      }
    }
  }

  return {
    myScoreArr: myScoreArr,
    scoreArr: scoreArr,
  }
}